package com.laoxu.test.rbacdemo.controller;


import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.laoxu.test.rbacdemo.common.PageRequest;
import com.laoxu.test.rbacdemo.common.Result;
import com.laoxu.test.rbacdemo.exception.AppException;
import com.laoxu.test.rbacdemo.model.SysUser;
import com.laoxu.test.rbacdemo.service.SysUserService;
import com.laoxu.test.rbacdemo.util.MD5Util;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.startup.UserConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  用户控制器
 * </p>
 *
 * @author laoxu
 * @since 2020-08-09
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/user")
public class SysUserController extends BaseController{
    private String message;

    @Autowired
    private SysUserService userService;

    @GetMapping("check/{username}")
    public boolean checkUserName(@NotBlank(message = "{required}") @PathVariable String username) {
        return this.userService.findByName(username) == null;
    }

    @GetMapping("/{username}")
    public SysUser detail(@NotBlank(message = "{required}") @PathVariable String username) {
        //UserServiceImpl中findByName方法改为调用baseMapper.findDetail(username)
        return this.userService.findByName(username);
    }

    @GetMapping
    @RequiresPermissions("user:view")
    public Map<String, Object> userList(PageRequest queryRequest, SysUser user) {
        return getDataTable(userService.findUserDetail(user, queryRequest));
    }

    @PostMapping("/add")
    @RequiresPermissions("user:add")
    public Result addUser(@RequestBody @Valid SysUser user) throws AppException {
        try {
            this.userService.createUser(user);
            return new Result().ok("新增用户成功");
        } catch (Exception e) {
            message = "新增用户失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }

    @PostMapping("/modify")
    @RequiresPermissions("user:update")
    public Result updateUser(@RequestBody @Valid SysUser user) throws AppException {
        try {
            this.userService.updateUser(user);
            return new Result().ok("修改用户成功");
        } catch (Exception e) {
            message = "修改用户失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }

    @PostMapping("/remove")
    @RequiresPermissions("user:delete")
    public Result deleteUsers(@NotBlank(message = "{required}") @RequestParam String userIds) throws AppException {
        try {
            String[] ids = userIds.split(StringPool.COMMA);
            this.userService.deleteUsers(ids);
            return new Result().ok("删除用户成功");
        } catch (Exception e) {
            message = "删除用户失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }


    @GetMapping("password/check")
    public boolean checkPassword(
            @NotBlank(message = "{required}") String username,
            @NotBlank(message = "{required}") String password) {
        String encryptPassword = MD5Util.encrypt(username, password);
        SysUser user = userService.findByName(username);
        if (user != null)
            return StringUtils.equals(user.getPassword(), encryptPassword);
        else
            return false;
    }

    @PostMapping("password")
    public Result updatePassword(
            @NotBlank(message = "{required}") String username,
            @NotBlank(message = "{required}") String password) throws AppException {
        try {
            userService.updatePassword(username, password);
            return new Result().ok("修改密码成功");
        } catch (Exception e) {
            message = "修改密码失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }

    @PostMapping("password/reset")
    @RequiresPermissions("user:reset")
    public Result resetPassword(@NotBlank(message = "{required}") String usernames) throws AppException {
        try {
            String[] usernameArr = usernames.split(StringPool.COMMA);
            this.userService.resetPassword(usernameArr);
            return new Result().ok("重置用户密码成功");
        } catch (Exception e) {
            message = "重置用户密码失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }

    @PostMapping("excel")
    @RequiresPermissions("user:export")
    public void export(PageRequest queryRequest, @RequestBody SysUser user, HttpServletResponse response) throws AppException {
        try {
            List<SysUser> users = this.userService.findUserDetail(user, queryRequest).getRecords();
            ExcelKit.$Export(SysUser.class, response).downXlsx(users, false);
        } catch (Exception e) {
            message = "导出Excel失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }
}
